package com.yun.zf.admin.controller;

import com.yun.zf.common.admin.domain.LoginUser;
import com.yun.zf.common.admin.domain.SysAgent;
import com.yun.zf.common.admin.domain.SysMenu;
import com.yun.zf.common.admin.dto.UserInfoDTO;
import com.yun.zf.common.admin.model.LoginBodyMo;
import com.yun.zf.common.annotation.LogPrint;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.constant.PactConstants;
import com.yun.zf.common.utils.ServletUtils;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.exception.ExceptionUtil;
import com.yun.zf.system.security.service.TokenService;
import com.yun.zf.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
@Api(tags = "用户登录系列")
@Slf4j
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysAgentService agentService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private SysPermissionService sysPermissionService;


    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    /**
     * 登录方法
     * 
     * @param
     * @param
     * @param
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    @LogPrint(description = "用户登录")
    public Response login(@RequestBody LoginBodyMo loginBody)
    {
        Map<String,Object> map = new HashMap<>();
        try {
            // 生成令牌
            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());
            map.put(Constants.TOKEN, token);
            // 设置前端过期时间
            map.put("expire",new Date().getTime() + expireTime * (50*1000));
        }catch (Exception e){
            log.error(ExceptionUtil.getExceptionMessage(e));
          return   Response.error(e.getMessage());
        }


        return Response.success(map);
    }




    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation(value = "获取用户信息")
    public Response<UserInfoDTO> getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 通过userId 获取用户管理员信息
      SysAgent agent = agentService.getInfoByUserId(loginUser.getUserId());

        // 角色集合
        Set<String> roles = sysPermissionService.getRolePermission(loginUser.getUserId());
        // 权限集合
        Set<String> permissions = sysPermissionService.getMenuPermission(loginUser.getUserId());
        // 验证角色决定是否要展示城市切换
        String dvalue = dictDataService.getValue(PactConstants.MANAGER, PactConstants.MANAGER_KEY);
        Boolean flage = permissionService.hasAnyRoles(dvalue);
        log.info("是否为管理人员角色{}",flage);
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUser(agent);
        userInfoDTO.setRoles(roles);
        userInfoDTO.setPermissions(permissions);
        userInfoDTO.setIsShowCity(flage);
        return Response.success(userInfoDTO);
    }




    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @ApiOperation(value = "获取路由")
    public Response getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(loginUser.getUserId());
        return Response.success(menuService.buildMenus(menus));
    }


    @PostMapping("/getPermission")
    @ApiOperation(value = "获取权限")
    public Response getPermission()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        return Response.success(loginUser.getPermissions());
    }
}
